package demo.sql;

import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;

public class D02WindownTumble {


    public static void main(String[] args) {

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        StreamTableEnvironment tableEnvironment = StreamTableEnvironment.create(env);


        //
        String sourceSql = "CREATE TABLE datagen (" +
                "    f_sequence INT," +
                "    f_random INT," +
                "    f_random_str STRING," +
                "    ts AS localtimestamp," +
                "    WATERMARK FOR ts AS ts - interval '90' second" +
                "  ) WITH (" +
                "    'connector' = 'datagen'," +
                "    'rows-per-second'='1'," +
                "    'fields.f_sequence.kind'='sequence'," +
                "    'fields.f_sequence.start'='1'," +
                "    'fields.f_sequence.end'='10000'," +
                "    'fields.f_random.min'='1'," +
                "    'fields.f_random.max'='100'," +
                "    'fields.f_random_str.length'='10'" +
                "  )";

        // table(tumble(table join_view, descriptor (stime), interval '60' second ))
        String process =
                "create view result1 as " +
                "select " +
                "  window_start stime," +
                "  window_end etime," +
                "  count(1) as cnt " +
                "from " +
                "  table(tumble(table datagen, descriptor(ts), interval '60' second)) " +
                "group by " +
                "  window_start, window_end";

        String sinkSql =
                "  CREATE TABLE print_table (" +
                "    `stime` timestamp(3) NOT NULL," +
                "    `etime` timestamp(3) NOT NULL," +
                "     nowts timestamp(3) NOT NULL," +
                "    f_random INT NOT NULL," +
                "    cnt BIGINT NOT NULL" +
                "    ) WITH (" +
                "    'connector' = 'print'" +
                "  )";

        String execSql = "INSERT INTO print_table select stime,etime,localtimestamp as nowts, f_random,cnt  from result1";

        tableEnvironment.executeSql(sourceSql);
        tableEnvironment.executeSql(process);
        tableEnvironment.executeSql(sinkSql);
        tableEnvironment.executeSql(execSql);


    }

}
